<?php
$adm_menu = "1";

include("config.php");
if (!isset($_SESSION["auser"]) || $_SESSION["auser"] == "" || $_SESSION['agroup'] != "WEB_ADMIN") header('Location: index.php');

$db_www = new DB($server_username,$server_pass,$server_db,$server,$driver);
$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);


if (isset($_REQUEST["act"])){
	if ($_REQUEST["act"] == "save") {
		$err = "";
		if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {
			if (!isset($_POST["aparatoid"]) || trim($_POST["aparatoid"])=="") {
				$err .= "Neužpildytas laukas 'Aparato id'<br>";
			}
		}
		if (!isset($_POST["apmokejimorusis"]) || trim($_POST["apmokejimorusis"])=="") {
			$err .= "Neužpildytas laukas 'Apmokejimo rusis'<br>";
		}
		if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {
			if (!isset($_POST["kortelesnr"]) || trim($_POST["kortelesnr"])=="") {
				$err .= "Neužpildytas laukas 'Korteles nr'<br>";
			}	
		}
		if (!isset($_POST["data"]) || trim($_POST["data"])=="") {
			$err .= "Neužpildytas laukas 'Data'<br>";
		}
		if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {
			if (!isset($_POST["znr"]) || trim($_POST["znr"])=="") {
				$err .= "Neužpildytas laukas 'Znr'<br>";
			}
		}		
		if(!preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/',$_POST["data"])){
			$err .= "Neteisingas datos formatas<br>";
		}
		
		if ($err == "") {
			$sql = "create table #tt_eilutes(barkodas varchar(100),preke varchar(100),kiekis varchar(100),kaina varchar(100),mokesciai varchar(100),eilid varchar(100));";
			$db_rdata->execute($sql);	
			$cnt = 0;
			foreach($_POST as $key=>$value)
			{
				if (preg_match('#^kiekis#', $key) === 1) {
					$eilid = substr($key,6);
					$barkodas = addslashes_mssql($_POST["barkodas".$eilid]);
					$sql = "select 
											case when pr.n17_mokestis = 0 then 0
											when pr.N17_TAX = 1 then t.n12_a_tax
											when pr.N17_TAX = 2 then t.n12_b_tax
											when pr.N17_TAX = 3 then t.n12_c_tax
											when pr.N17_TAX = 4 then t.n12_d_tax
											when pr.N17_TAX = 5 then t.n12_e_tax
											when pr.N17_TAX = 6 then t.n12_f_tax
											when pr.N17_TAX = 7 then t.n12_g_tax
											when pr.N17_TAX = 8 then t.n12_h_tax
											else
											0
											end as pvm
											 from n37_pmat p, n17_prod pr , N12_TAX t
											where cast(p.N37_BAR_KODAS as numeric(15,0))= '".$barkodas."'
											and p.N37_KODAS_PS = pr.N17_KODAS_PS
											and t.N12_KODAS_XS='PVM'";
					
					$pvm = $db_www->returnInfo($sql);
					//echo $sql;
			
					if (!empty($pvm)){	
						if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {
							$enr = "''";	
						} else {
							$enr = $_POST["eilid".$eilid];
						}
						$sql = "insert into #tt_eilutes VALUES('".$barkodas."','"."','".addslashes_mssql(str_replace(",",".",$_POST["kiekis".$eilid]))."','".addslashes_mssql(str_replace(",",".",$_POST["kaina".$eilid]))."','".$pvm["pvm"]."',".$enr.");";
						//echo $sql;
						$db_rdata->execute($sql);
						$cnt++;
					}					
				}
			}
			if ($cnt > 0) {
			    if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {	//naujas kvitas
					$sql = "exec web_insert_voucher "
					. "@aparatoid='".addslashes_mssql($_POST["aparatoid"])."',"
					. "@apmokejimorusis='".addslashes_mssql($_POST["apmokejimorusis"])."',"
					. "@kortelesnr='".addslashes_mssql($_POST["kortelesnr"])."',"
					. "@kvitonr2='',"
					. "@data='".addslashes_mssql($_POST["data"])."',"	
					. "@znr='".addslashes_mssql($_POST["znr"])."'";
					$db_rdata->execute($sql);
				} else { //koregavimas
					$sql = "exec web_upd_voucher "
					. "@galvosid='".addslashes_mssql($_REQUEST["id"])."',"
					. "@apmokejimorusis='".addslashes_mssql($_POST["apmokejimorusis"])."',"
					. "@kortelesnr='".addslashes_mssql($_POST["kortelesnr"])."',"
					. "@data='".addslashes_mssql($_POST["data"])."'";	
					$db_rdata->execute($sql);				
				}				
				header('Location: vouchers.php?sub=Rodyti');
			}			
		}		
	} 
} 
	
include("header.php");
include("menu.php");

if (isset($_REQUEST["id"]) && $_REQUEST["id"] != "") {
	$tit = "Kvito koregavimas";	
	$mod = " DISABLED";
	
	$vouncher_query = str_replace("<import>", " 1=1 ", $vouncher_query);
	$vouncher_query .= " and kvitogalva.id = '".addslashes_mssql($_REQUEST["id"])."'";
	
	$rs = $db_rdata->returnInfo($vouncher_query);
	if (empty($rs)) {
		$data = "";
		$aparatoid = "";
		$apmokejimorusis = "";
		$kortelesnr = "";
		$kvitonr2 = "";
		$znr = "";	
	} else {
		$data = $rs["data1"];
		$aparatoid = htmlspecialchars($rs["AparatoID"]);
		$apmokejimorusis = htmlspecialchars($rs["ApmokejimoRusis"]);
		$kortelesnr = htmlspecialchars($rs["KortelesNr"]);
		$kvitonr2 = htmlspecialchars($rs["KvitoNr2"]);
		$znr = htmlspecialchars($rs["Znr"]);		
	}
} else {
	$tit = "Naujas kvitas";	
	$mod = "";	
	$data = date("Y-m-d H:i");
	$aparatoid = "";
	$apmokejimorusis = "";
	$kortelesnr = "";
	$kvitonr2 = "";
	$znr = "";
}

?>
<form method="post" name='forma' action='voucher.php?act=save'>
<table class="innercont" cellspacing="0" cellpadding="10" border="0">
<tr><td class="leftcol2">
<?php
if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {	
	echo "<input type='hidden' name='id' value=''>";
} else {
	echo "<input type='hidden' name='id' value='".$_REQUEST["id"]."'>";
}
?>
<input class='but bgwhite nopad' type = "submit" value = "Išsaugoti"><br><br>
<Button id='unblockButton' class='but bgwhite nopad' onclick="window.location='vouchers.php?sub=Rodyti';return false;">Atgal</Button>
</td><td class="centercol">
<?php
if (isset($err) && $err != ""){
	echo "<p style='background-color:transparent;color:red;font-weight:bold;font-size:10px;'>".$err."</p>";
}
?>
<div class="title2"><?php echo $tit?></div>
<div>Kvito galva</div>
<table width="100%" border="0">
<tr><td valign="top" class="fieldtitle">Aparato ID:</td><td valign="top" colspan="2" class="fieldtitle">Apmokejimo rusis:</td></tr>
<tr><td valign="top">
<input class="inp" type='text' name="aparatoid" value="<?php echo $aparatoid;?>" <?php echo $mod;?>><br>
</td><td valign="top" colspan="2">
<input class="inp" type='text' name="apmokejimorusis" value="<?php echo $apmokejimorusis;?>">
</td></tr>

<tr><td valign="top" class="fieldtitle">Korteles nr:</td><td valign="top" colspan="2" class="fieldtitle"><!--Kvito nr 2:--></td></tr>
<tr><td valign="top">
<input class="inp" type='text' name="kortelesnr" value="<?php echo $kortelesnr;?>"><br>
</td><td valign="top" colspan="2">
<!--input class="inp" type='text' name="kvitonr2" value="<?php echo $kvitonr2;?>" <?php echo $mod;?>-->
</td></tr>

<tr><td valign="top" class="fieldtitle">Data:</td><td valign="top" colspan="2" class="fieldtitle">Znr</td></tr>
<tr><td valign="top">
<input class="inp" type='text' name="data" value="<?php echo $data;?>"><br>
</td><td valign="top" colspan="2">
<input class="inp" type='text' name="znr" value="<?php echo $znr;?>" <?php echo $mod;?>><br>
</td></tr>

</table>
<script>
var rowCount = 1;
var visoSuma = 0;

function recalcRow(rowid){
	
	recalcAllRows();
}

function recalcAllRows(){
    visoSuma = 0;
	
	
	var inputs = document.getElementsByTagName('input');
	for (var i = 0; i < inputs.length; ++i) {
	  if (inputs[i].id.startsWith("kaina")) {
            var num = inputs[i].value.replace(",",".");
			if (isNumber(num)) {
				visoSuma += roundToTwo( num);			
			}
		
	  }  
	}
	//var mok = document.getElementById("visoMokesciai");
	//if (mok != null) mok.innerHTML = visoMokesciai;
	
	var suma = document.getElementById("visoSuma");
	if (suma != null) suma.innerHTML = visoSuma;	
}

if (typeof String.prototype.startsWith != 'function') {
  // see below for better implementation!
  String.prototype.startsWith = function (str){
    return this.indexOf(str) == 0;
  };
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
function addRow(){
	var table = document.getElementById("myTable");
	var row = table.insertRow(rowCount+1);
	row.id = 'row'+(rowCount+1);
	var cell1 = row.insertCell(0);
	var cell2 = row.insertCell(1);
	var cell3 = row.insertCell(2);
	var cell4 = row.insertCell(3);


	cell1.innerHTML = '<input class="inp" type="text" name="barkodas'+(rowCount+1)+'" id="barkodas'+(rowCount+1)+'" value="">';
	cell2.innerHTML = '<input class="inp" type="text" name="kiekis'+(rowCount+1)+'" id="kiekis'+(rowCount+1)+'" value="" onchange="recalcRow('+(rowCount+1)+');">';
	cell3.innerHTML = '<input class="inp" type="text" name="kaina'+(rowCount+1)+'" id="kaina'+(rowCount+1)+'" value="" onchange="recalcRow('+(rowCount+1)+');">';
	cell4.innerHTML = '<button class="but bgwhite nopad" onclick="delRow('+(rowCount+1)+');return false;">Trinti</button>';

	rowCount++;
}

function delRow(id){
	var row = document.getElementById("row"+id);
	if (row != null) {
		row.parentNode.removeChild(row);
	}
	recalcAllRows();
	rowCount--;
}

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}
</script>
<div>Kvito eilutės</div>
<table id="myTable" cellspacing="0" cellpadding="5" class="innercont3" style="width:100%;">
<tr><th>Barkodas</th><th>Kiekis</th><th>Suma</th><th></th></tr>
<?php
$visoSuma = 0;
$visoMokesciai = 0;
if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {
?>
<tr>
<td><input class="inp" type='text' name="barkodas1" id="barkodas1" value=""></td>
<td><input class="inp" type='text' name="kiekis1" id="kiekis1" value=""></td>
<td><input class="inp" type='text' name="kaina1" id="kaina1" value="" onchange="recalcRow(1);"></td>
<td></td>
</tr>
<?php
} else {
$ns = $db_rdata->returnList("SELECT * from KvitoEilute where galvosid = '".addslashes_mssql($_REQUEST["id"])."'");
$eilnr = 0;
foreach ($ns as $eilute) {
$eilnr++;
?>
<tr>
<td><input class="inp" type='text' name="barkodas<?php echo $eilnr;?>" id="barkodas<?php echo $eilnr;?>" value="<?php echo htmlspecialchars($eilute["Barkodas"]);?>"></td>
<td><input class="inp" type='text' name="kiekis<?php echo $eilnr;?>" id="kiekis<?php echo $eilnr;?>" value="<?php echo htmlspecialchars($eilute["Kiekis"]);?>"></td>
<td><input class="inp" type='text' name="kaina<?php echo $eilnr;?>" id="kaina<?php echo $eilnr;?>" value="<?php echo htmlspecialchars(($eilute["Kiekis"]*$eilute["Kaina"]));?>" onchange="recalcRow(<?php echo $eilnr;?>);">
<input type='hidden' name="eilid<?php echo $eilnr;?>" id="eilid<?php echo $eilnr;?>" value="<?php echo htmlspecialchars($eilute["ID"]);?>">
</td>
<td></td>
</tr>
<?php
$visoSuma += ($eilute["Kiekis"]*$eilute["Kaina"]);
}

}
?>
<tr><td></td><td></td><td><div id="visoSuma"><?php echo $visoSuma;?></div></td><td></td></tr>
</table>
<?php
if (!isset($_REQUEST["id"]) || $_REQUEST["id"] == "") {
?>
<button class="but bgwhite nopad" onclick="addRow();return false;">Nauja eilutė</button>
<?php
}
?>
</td></tr>
</table>
</form>
<?php
include("footer.php");
?>